<template>
  <div class="comWidth">
    <div class="addLink">
      <el-button @click="deleteAll" type="danger" icon="el-icon-delete" circle></el-button>
      <router-link to="/add">
        <el-button type="primary" circle><i class="el-icon-circle-plus-outline"></i></el-button>
      </router-link>
    </div>
    <el-table
      border
      ref="multipleTable"
      :data="gists"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection">
      </el-table-column>
      <el-table-column
        label="id">
        <template slot-scope="scope">{{ scope.row.created_at | time}}</template>
      </el-table-column>
      <el-table-column
        prop="url"
        label="链接地址"
        width="500">
      </el-table-column>
      <el-table-column
        prop="description"
        label="详情描述"
        show-overflow-tooltip>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <router-link :to="{ name: 'Edit', query: { id: scope.row.id  }}">
            <i class="el-icon-edit"></i>
          </router-link>
          <i class="el-icon-delete" :id="scope.row.id" @click="deleteGist"></i>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-box">
      <button
        :disabled="!this.links.hasOwnProperty('prev')"
        :class="[{mouseDisabled:!this.links.hasOwnProperty('prev')},{nextBtn:true}]"
        @click="prevPage" class="prevBtn">
        <i class="el-icon-arrow-left"></i>
      </button>
      <ul class="page">
        <li v-for="(page,idx) in pager" @click="currentPage(idx)" :class="{active:selected === idx}">{{page.count}}</li>
      </ul>
      <button :disabled="!this.links.hasOwnProperty('next')"
              :class="[{mouseDisabled:!this.links.hasOwnProperty('next')},{nextBtn:true}]"
              @click="nextPage">
        <i class="el-icon-arrow-right"></i>
      </button>
      <span class="fl totalPage">共{{pageCount}}页</span>
      <div class="jump">
        <span>跳至</span>
        <input type="text" v-model="currentValue">
        <span>页</span>
        <button @click="changePage(currentValue)">跳转</button>
      </div>
    </div>
  </div>
</template>

<script>
  import http from "axios"
  //  import moment from "moment"
  import timeStamp from "time-stamp"
  import queryString from "query-string"

  export default {
    name: "Read",
    data(){
      return {
        gists: [],
        links: {},
        pager: [],
        pageCount: 1,
        selected:0,
        currentValue: "",
        getPage: function (url, funct) {
          http.get(url, {
            headers: {
              "Authorization": "token " + localStorage.getItem("token")
            }
          }).then((r) => {
            this.gists = r.data;
            this.links = {};
            var _self = this;
            r.headers.link.split(",").forEach(function (item) {
              var href = item.match(/[<](.+)[>]; rel="(.+)"/);
              // _self.links[href[2]]=href[1];
              _self.$set(_self.links, href[2], href[1]);
            });
            if (typeof funct === "function") {
              funct.call(_self);
            }
          })
            .catch();
        }
      }
    },
    filters: {
      time: function () {
        return timeStamp('YYYYMMDD HH:mm:ss');
      }
    },
    mounted(){
      this.getPage("https://api.github.com/gists?page=1&per_page=4", function () {
        this.pageCount = parseInt(this.links["last"].match(/\d/)[0]);
        for (var i = 1; i <= this.pageCount; i++) {
          this.pager.push({
            count: i
          });
        }
        this.currentValue = 2;
      });
    },
    methods: {
      changePage(){
        this.currentValue = parseInt(this.currentValue);
        if (this.currentValue <= this.pageCount && this.currentValue >= 0) {
          var str = "https://api.github.com/gists?page=num&per_page=4";
          this.getPage(str.replace(/num/, this.currentValue), function () {
//              如何动态加class;
           this.selected = this.currentValue -1;
          });
        } else {
          this.currentValue = this.pageCount;
        }
        console.log(this.currentValue);
      },
      currentPage(idx){
        var str = "https://api.github.com/gists?page=num&per_page=4";
        this.getPage(str.replace(/num/, idx + 1), function () {
          this.selected =idx;
          if (idx < this.pageCount - 1) {
            this.currentValue = idx + 2;
          } else {
            this.currentValue = this.pageCount;
          }
        });
      },
      prevPage(){
        this.getPage(this.links.prev, function () {
        });
      },
      nextPage(){
        this.getPage(this.links.next, function () {
        });
      },
      deleteAll(){
        var _self = this;
        this.multipleSelection.forEach(function (item) {
          http.delete("https://api.github.com/gists/" + item.id, {
            headers: {
              "Authorization": "token " + localStorage.getItem("token")
            }
          })
            .then((r) => {
              _self.gists = _self.gists.filter(val => val.id !== item.id);
            })
            .catch();
        });
      },
      deleteGist(e) {
        var selectId = e.target.id;
        http.delete("https://api.github.com/gists/" + selectId, {
          headers: {
            "Authorization": "token " + localStorage.getItem("token")
          }
        })
          .then((r) => {
            this.gists = this.gists.filter(val => val.id !== selectId);
            window.confirm("删除成功");
          })
          .catch();
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      }
    }
  }
</script>

<style scoped>
  .addLink{
    text-align: right;
    margin-bottom: 10px;
  }
  .page-box button.prevBtn,
  .page-box button.nextBtn,
  .jump button {
    background-color: #fff;
    float: left;
    height: 32px;
    line-height: 32px;
    width: 32px;
    border: 1px solid #d9d9d9;
    cursor: pointer;
  }

  /*鼠标禁止*/
  .page-box button.mouseDisabled {
    cursor: not-allowed;
  }

  ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
  }

  .page-box {
    text-align: center;
    display: inline-block;
    margin-top: 20px;
  }

  .page:after {
    content: '';
    clear: both;
    display: block;
  }

  .page {
    width: auto;
    float: left;
  }

  .page li {
    height: 30px;
    line-height: 30px;
    width: 30px;
    border: 1px solid #d9d9d9;
    font-size: 12px;
    cursor: pointer;
    float: left;
    margin: 0 2px;
  }

  .page li:hover,
  .page li.active {
    color: #409EFF;
    border-color: #409EFF;
  }
  .jump {
    float: left;
    font-size: 12px;
    padding-left: 20px;
    position: relative;
    top: -1px;
    height: 26px;
  }
  .jump button {
    float: none;
    width: 60px;
  }
  .jump input {
    width: 30px;
    height: 30px;
    line-height: 30px;
    border: 1px solid #d9d9d9;
    text-align: center;
  }

  .totalPage {
    height: 30px;
    line-height: 30px;
    padding-left: 10px;
  }
</style>
